<template>
  <el-dialog
    v-model="show"
    title="分配角色"
    width="30%"
    :before-close="handleClose"
  >
    <el-select
      v-model="selectedRoleIds"
      multiple
      placeholder="Select"
      style="width: 240px"
    >
      <el-option
        v-for="item in options"
        :key="item.value"
        :label="item.label"
        :value="item.value"
      />
    </el-select>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="sureFn"> 确定 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { user } from "@/api";
import { ref, reactive, computed, watch } from "vue";

const props = defineProps({
  show: {
    type: Boolean,
    default: false,
  },
  data: {
    type: Number,
    default: 0,
  },
});

const handleClose = () => {
  emit("hide");
  selectedRoleIds.value = [];
};

const selectedRoleIds = ref<number[]>([]);

interface IState {
  roleList: IRoleModel[];
}
const state = reactive<IState>({
  roleList: [],
});
user.getRoleListApi().then((res) => {
  if (res.code === 200) {
    state.roleList = res.data;
  }
});

const options = computed(() => {
  return state.roleList.map((item) => ({
    value: item.id,
    label: item.name,
  }));
});

// 子传父
const emit = defineEmits(["hide"]);

watch(
  () => props.data,
  () => {
    user.getRoleListByAdminIdApi(props.data).then((res) => {
      if (res.code === 200) {
        selectedRoleIds.value = res.data.map((item) => item.id);
      }
    });
  }
);

const sureFn = () => {
  user.updateRolesApi({
    adminId: props.data,
    roleIds: selectedRoleIds.value,
  });
};
</script>

<style scoped></style>
